﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using MusicWorks.Web.Logic.Helpers;
using MusicWorks.Web.Logic.ShoppingService.svc;

namespace MusicWorks.Web.Logic.Modules
{
    public class SessionModule : IHttpModule
    {
        HttpApplication _applicationContext;
        ISessionValueProvider _sessionValueProvider;
        IShoppingService _shoppingService;

        public SessionModule() : this(new CookieSessionValueProvider(), ServiceBroker.CreateShoppingServiceInstance()) { }
        public SessionModule(ISessionValueProvider sessionValueProvider, IShoppingService shoppingService)
        {
            _sessionValueProvider = sessionValueProvider;
            _shoppingService = shoppingService;
        }

        public void Dispose()
        {
            _applicationContext.BeginRequest -= Context_BeginRequest;
        }

        public void Init(HttpApplication context)
        {
            _applicationContext = context;
            _applicationContext.BeginRequest += Context_BeginRequest;
        }

        void Context_BeginRequest(object sender, EventArgs e)
        {
            var userId = _sessionValueProvider.UserId;
            if (userId == Guid.Empty)
            {
                _sessionValueProvider.UserId = Guid.NewGuid();
            }
        }
    }
}
